﻿<%@ WebHandler Language="C#" Class="SuspendContainerManageHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Data;
//Description: 批次冻结、释放处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-04-15
public class SuspendContainerManageHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "InitPageData": //初始化页面数据
                    InitPageData(context);
                    break;
                case "GetContainerInfo": //获取主批次列表
                    GetContainerInfo(context);
                    break;
                case "GetContainerDetails": //获取批次详细列表
                    GetContainerDetails(context);
                    break;
                case "OperContainerStep": //保存批次暂停或释放数据
                    OperContainerStep(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";

            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 初始化页面数据
    /// </summary>
    public void InitPageData(HttpContext context)
    {
        string strRole_GYY = ""; //工艺员
        strRole_GYY = m_CommonObj.GetEnterpriseAttributes("工艺员角色");
        if (string.IsNullOrWhiteSpace(strRole_GYY))
        {
            strRole_GYY = "StepManageTFW";
        }
        DataTable employeedt = new DataTable();
        if (m_UserInfo.Roles.Contains(strRole_GYY))//如果当前人为工艺员，则只显示自己
        {
            employeedt.Columns.Add("EMPLOYEEID");
            employeedt.Columns.Add("FULLNAME");
            DataRow dr = employeedt.NewRow();
            dr["EMPLOYEEID"] = m_UserInfo.EmployeeID;
            dr["FULLNAME"] = m_UserInfo.FullName;
            employeedt.Rows.Add(dr);
        }
        else
        {
            employeedt = m_CommonObj.GetEmplyeeListByRole("工艺员", m_UserInfo.FactoryID);
            employeedt = employeedt.DefaultView.ToTable(false, new string[] { "EMPLOYEEID", "FULLNAME" });
            DataRow dr = employeedt.NewRow();
            dr["EMPLOYEEID"] = "";
            dr["FULLNAME"] = "全部";
            employeedt.Rows.InsertAt(dr, 0);
        }
        uMESProcessResult result = new uMESProcessResult();
        result.Result = employeedt.Rows.Count > 0 ? true : false;
        result.Message = result.Result ? "" : "没有工艺员数据";
        result.DBTable = employeedt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取主批次列表
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerInfo(HttpContext context)
    {
        string mfgOrderName = context.Request["mfgOrderName"].ToString();//订单号
        string productName = context.Request["productName"].ToString();//件号
        string containerName = context.Request["containerName"].ToString();//批次号
        string techEmployeeId = context.Request["techEmployeeId"].ToString();//工艺员
        string status = context.Request["status"].ToString();//状态
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        string reason = context.Request["reason"].ToString();
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("factoryID", m_UserInfo.FactoryID);
        para.Add("status", status);
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        if (!string.IsNullOrWhiteSpace(mfgOrderName))
        {
            para.Add("mfgOrderName", mfgOrderName);
        }
        if (!string.IsNullOrWhiteSpace(productName))
        {
            para.Add("productName", productName);
        }
        if (!string.IsNullOrWhiteSpace(containerName))
        {
            para.Add("containerName", containerName);
        }
        if (!string.IsNullOrWhiteSpace(techEmployeeId))
        {
            para.Add("techEmployeeId", techEmployeeId);
        }
        if (!string.IsNullOrWhiteSpace(reason) && status == "1")//已暂停查询，需带原因
        {
            para.Add("reason", reason.TrimEnd(','));
        }
        uMESProcessResult result = m_ContainerObj.GetOperStopContainerInfo(para);
        result.Message = result.Result ? "获取成功" : result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取冻结批次详细信息
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerDetails(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        string reason = context.Request["reason"].ToString();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择主批次数据" }));
            return;
        }
        if (dt.Rows[0]["Ishold"].ToString() == "是")
        {
            para.Add("isHold", "1");
        }
        else { para.Add("isHold", "0"); }
        string valuestr = "";
        foreach (DataRow item in dt.Rows)
        {
            if (!string.IsNullOrWhiteSpace(valuestr))
            {
                valuestr += " OR ";
            }
            if (item["ContainerType"].ToString() == "7")
            {
                valuestr += string.Format(" (cu.togetherflag = '{0}'", item["togetherflag"].ToString());
            }
            else
            {
                valuestr += string.Format(" (cu.containername = '{0}'", item["togetherflag"].ToString());
            }
            valuestr += string.Format(" AND cu.mfgorderid='{0}'", item["MfgOrderID"].ToString());
            valuestr += string.Format(" AND cu.workflowstepid = '{0}')", item["WorkflowStepID"].ToString());
        }
        if (valuestr.Contains("OR"))
        {
            para.Add("valueStr", "(" + valuestr + ")");
        }
        else
        {
            para.Add("valueStr", valuestr);
        }
        if (!string.IsNullOrWhiteSpace(reason))//已暂停查询，需带原因
        {
            para.Add("reason", reason.TrimEnd(','));
        }
        DataTable resDt = m_ContainerObj.GetOperStopContainerDetailInfo(para);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "获取成功", DBTable = resDt }));
    }
    /// <summary>
    /// 更新批次暂停或者释放
    /// </summary>
    /// <param name="context"></param>
    public void OperContainerStep(HttpContext context)
    {
        int type = int.Parse(context.Request["type"].ToString());
        string productName = context.Request["productName"].ToString();
        string productId = context.Request["productId"].ToString();
        string reason = context.Request["reason"].ToString();
        string message = "更新成功";
        bool isVaild = true;
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择批次数据" }));
            return;
        }
        string contaienrids = "";
        foreach (DataRow item in dt.Rows)
        {
            contaienrids += "," + item["ContainerID"].ToString();
        }
        contaienrids = "'" + contaienrids.Substring(1).Replace(",", "','") + "'";
        if (m_ContainerObj.OperContainerStop(contaienrids, type))//更新批次暂停状态
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            type = type == 0 ? 3 : 2;
            foreach (DataRow item1 in dt.Rows)
            {
                para.Clear();
                para.Add("containerid", item1["ContainerID"].ToString());
                para.Add("containername", item1["ContainerName"].ToString());
                para.Add("productid", productId);
                para.Add("productname", productName);
                para.Add("operatorid", m_UserInfo.EmployeeID.ToString());
                para.Add("operreason", reason);
                para.Add("qty", item1["Qty"].ToString());
                para.Add("opertype", type.ToString());
                if (!m_ContainerObj.AddDeleteContainerRecord(para))
                {
                    isVaild = false;
                    message += " 批次：" + para["containername"] + (type == 2 ? "暂停" : "释放") + "失败";
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isVaild, Message = message }));
    }
}